using System.Text.RegularExpressions;

namespace BomComparison.Algorithm.Comparers;

public static partial class PartReferenceParser
{
    [GeneratedRegex("[a-zA-Z]+")] 
    private static partial Regex LetterCountRegex();

    public static HashSet<string> StringToHashSet(string partReference)
    {

        var designator = StringToList(partReference);
        return new HashSet<string>(designator);
    }

    /// <summary>
    /// 分割位号,将位号字符串分割为 List
    /// </summary>
    /// <param name="partReference"></param>
    /// <returns></returns>
    public static List<string> StringToList(string partReference)
    {
        //return partReference.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

        if (string.IsNullOrEmpty(partReference))
        {
            return new List<string>();
        }

        string[] stringSeparators = [","];
        return partReference.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)
                            .Select(s => s.Trim())
                            .Where(s => !string.IsNullOrEmpty(s))
                            .ToList();
    }



    /**
    * Builds back the original style of reference partReference string.
    * 重建原始的位号字符串
    * @return Reference designators list as a string.
    * 将位号List 转为字符串
    */
    public static string ListToString(List<string> designator)
    {
        ArgumentNullException.ThrowIfNull(designator);

        return string.Join(",", designator);
    }

    //删除空白字符
    public static string RemoveWhitespace(string input)
    {
        return string.IsNullOrEmpty(input) ? input : new string(input.Where(ch => !char.IsWhiteSpace(ch)).ToArray());
    }

    // 计算位号个数
    public static int GetPartReferenceCount(string partReference)
    {
        return string.IsNullOrEmpty(partReference) ? 0 : LetterCountRegex().Matches(partReference).Count;
    }

    private static bool IsValidReference(string refDes)
    {
        var match = IsValidRegex().Match(refDes);
        return match.Success; // 验证格式如R1,C100
    }

    [GeneratedRegex("^[A-Z]+\\d+$")] 
    private static partial Regex IsValidRegex();
}
